/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sigmatrix.h5.dao.DisRebateActivityDao;
import com.sigmatrix.h5.entity.DisDealer;
import com.sigmatrix.h5.entity.DisRebateActivity;
import com.sigmatrix.h5.entity.DisRebateCondition;
import com.sigmatrix.h5.entity.DisRebateScanCode;
import com.sigmatrix.h5.enums.ConditionType;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.service.DisDealerService;
import com.sigmatrix.h5.service.DisRebateActivityService;
import com.sigmatrix.h5.service.DisRebateConditionService;
import com.sigmatrix.h5.service.DisRebateScanCodeService;
import com.sigmatrix.h5.utils.Assert;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Constants;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.web.mode.RebateActivityInfo;
import com.sigmatrix.sc.jdbc.common.service.ServiceImpl;

/**
 *@ClassName: DisRebateActivityServiceImpl
 *@Description: 
 *@author MH
 *@date 2017年8月15日 下午5:28:32
 */
@Service
public class DisRebateActivityServiceImpl extends ServiceImpl<DisRebateActivity,Integer> implements DisRebateActivityService{
	
	@Autowired
	private DisRebateActivityDao disRebateActivityDao;
	
	@Autowired
	private DisRebateConditionService disRebateConditionService;
	@Autowired
	private DisDealerService disDealerService;
	@Autowired
	private DisRebateScanCodeService disRebateScanCodeService;
	
	@Override
	public RebateActivityInfo determineActivityForHierarchyRebate(Integer dealerId,Integer productId) {
		List<RebateActivityInfo> activitys = disRebateActivityDao.determineActivityForHierarchyRebate(dealerId, productId);
		Assert.notNull(activitys, "没有查询到返利活动");
		for (RebateActivityInfo info : activitys) {
			if(CommonUtils.isEmpty(info.getConditionId())){
				return info;
			}else{
				DisRebateCondition condition = disRebateConditionService.transformCondition(info);
				boolean isSatisfiedCondition = disRebateConditionService.isSatisfiedCondition(condition, parseValue());
				if(isSatisfiedCondition) return info;
			}
			
		}
		throw new MessageException("不满足返利触发条件");
	}
	private Integer parseValue(){
		//终端店是3，一级经销商是4,二级经销商是5 。。。。
		if(CrmAcctType.DEALER.value.equals(SessionUtils.getAcctType())){
			DisDealer dealer = disDealerService.findById(SessionUtils.getDealerId());
			Assert.notNull(dealer, "账号异常，没有经销商ID");
			return dealer.getLevel()+3;
		}
		return SessionUtils.getAcctType().intValue();
	}
	@Override
	public RebateActivityInfo determineActivityForTerminalRebate(Integer dealerId, Integer productId,String openId,Integer writebackId) {
		List<RebateActivityInfo> activitys = disRebateActivityDao.determineActivityForTerminalRebate(dealerId, productId);
		Assert.notNull(activitys, "没有查询到返利活动");
		for (RebateActivityInfo info : activitys) {
			if(CommonUtils.isEmpty(info.getConditionId())) return info;
			//验证触发条件
			Integer count = 0; 
			if(ConditionType.NEW_SHOP_SCAN_TIME_IN_HOURE.value.equals(info.getConditionType())){
//				DisRebateScanCode first = disRebateScanCodeService.findFirstScanOfOpenIdByActivity(openId, null);
//				if(CommonUtils.isNotEmpty(first)){
//					//TODO 可能会包含这小时内结束的活动
//					count = disRebateScanCodeService.countByOpenIdInHoure(openId, info.getId(), first.getScanTime(), 1);
//				}
				List<DisRebateScanCode> list = disRebateScanCodeService.findByOpenId(openId);
				if(CommonUtils.isNotEmpty(list)) {
					DisRebateScanCode last = list.get(0);
					DisRebateScanCode first = list.get(list.size()-1);
					if(last.getScanTime().getTime()-first.getScanTime().getTime() > 60*60*1000)continue;
					count = list.size();
				}
			}else{
				//查询之前反填的次数
				count = disRebateScanCodeService.selectCountByDealerIdAndActivityId(writebackId, info.getId());
			}
			boolean satisfy = disRebateConditionService.isSatisfiedCondition(disRebateConditionService.transformCondition(info),++count);
			if(satisfy) return info;
		}
		return null;
	}

	@Override
	public void validateActivity(DisRebateActivity activity) {
		Assert.notNull(activity, "返利活动不能为空");
		//活动状态在数据库只有草稿，删除，未开始。未开始的数据才是发布的活动
		if(CommonUtils.isEmpty(activity) || activity.getStatus() != Constants.STATUS_NO_START){
			throw new MessageException("没有查询到返利活动，或活动未发布");
		}
		Date now = new Date();
		if(CommonUtils.isEmpty(activity.getStartTime()) || CommonUtils.isEmpty(activity.getEndTime())){
			throw new MessageException("该活动没有设置开始时间和结束时间");
		}
		if(now.before(activity.getStartTime())){
			throw new MessageException("活动尚未开始");
		}
		if(now.after(activity.getEndTime())){
			throw new MessageException("活动已经结束");
		}
	}
	
	@Override
	public DisRebateActivity getActivity(RebateActivityInfo info){
		DisRebateActivity activity = new DisRebateActivity();
		activity.setId(info.getId());
		activity.setStartTime(info.getStartTime());
		activity.setEndTime(info.getEndTime());
		activity.setStrategyId(info.getStrategyId());
		return activity;
	}

}
